<?php

namespace app\api\controller;

use app\api\validate\PublicValidate;
use app\api\validate\UserValidate;
use app\common\model\Ad;
use app\common\model\ConvertOrder;
use app\common\model\Essay;
use app\common\model\FosterGoods;
use app\common\model\FosterGoodsCategory;
use app\common\model\FosterOrder;
use app\common\model\Goods;
use app\common\model\GoodsCategory;
use app\common\model\GoodsSearch;
use app\common\model\JifenOrder;
use app\common\model\Order;
use app\common\model\ThirdUser;
use app\common\model\Users;
use app\common\service\PlatFormFactory;
use app\common\util\MyException;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;
use think\facade\View;

/**
 * @Apidoc\Title("首页")
 */
class IndexApi extends Base
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $store_title = getSysConfig('basic.store_title');
        $store_ico = getSysConfig('basic.store_ico');
        View::assign('store_title', $store_title);
        View::assign('store_ico', $store_ico);
    }

    /**
     * @Apidoc\Title("首页天气数据")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/tianqi")
     * @Apidoc\Param("province",type="string",require=true,default="",desc="省份")
     * @Apidoc\Param("city",type="string",require=true,default="",desc="城市名称")
     * @Apidoc\Returned("data", type="array",default="{}",desc="tem:实况温度,tem_night:最低温度,tem_day:最高温度,air:空气质量,win_speed:风力,humidity:湿度")
     */
    public function weather()
    {
        $province = input('province');
        $city = input('city');
        if ($province && $city) {
            //请求天气接口
            $province = str_replace('省', '', $province);
            $province = str_replace('市', '', $province);
            $city = str_replace('市', '', $city);
            $city = str_replace('区', '', $city);
            $url = "https://v0.yiketianqi.com/free/day?appid=61573727&appsecret=65wUbGOf&province=${province}&city=${city}";
        } else {
            //请求天气接口
            $ip = getIP();
            $url = "https://v0.yiketianqi.com/free/day?appid=61573727&appsecret=65wUbGOf&ip=$ip";
        }
        $content = file_get_contents($url);
        $data = json_decode($content, true);
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("获取app下载地址")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_xiazai_url")
     */
    public function get_app_download_url()
    {
        $data['app_download_url'] = getSysConfig('basic.app_download_url');
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("首页显示数据")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/Index")
     * @Apidoc\Returned("logo", type="string",default="www.shop.io/status",desc="logo")
     * @Apidoc\Returned("swiper", type="array",default="{'ad_link':'#index','image':'www.shop.io/status'}",desc="轮播图")
     * @Apidoc\Returned("swiper_menu", type="array",default="{'ad_link':'#index','ad_name':'1','image':'www.shop.io/status'}",desc="导航")
     * @Apidoc\Returned("video_menu", type="array",default="{'ad_id':'1','ad_link':'#index','ad_name':'','image':'','video':'w'}",desc="导航")
     * @Apidoc\Returned("notice", type="array",default="['title':'测试1','id':'1']",desc="公告")
     */
    public function index()
    {
        //定义存储返回数据的变量
        $data = [];
        $site_url = SITE_URL;
        //首页logo
        $data['logo'] = cdnurl(getSysConfig('basic.store_ico'), true);
        //首页轮播数据
        $data['swiper'] = Ad::where('open=1 and ad_type=1')
            ->field("ad_link,concat('$site_url',image) as image,concat('$site_url',image) as poster,concat('$site_url',video) as video,type")
            ->order('sort asc,ad_id desc')
            ->select()
            ->each(function ($item) {
                if ($item['type'] == 1) {
                    $item['type'] = 'image';
                } else {
                    $item['type'] = 'video';
                    $item['image'] = $item['video'];
                }
                return $item;
            })
            ->toArray();
        //首页导航数据
        $data['swiper_menu'] = Ad::where('open=1 and ad_type=2')
            ->field("ad_name,ad_link,concat('$site_url',image) as image,jump_type,app_id")
            ->order('sort asc,ad_id desc')
            ->select()
            ->toArray();
        //首页广告视频数据
        $data['video_menu'] = Ad::where('open=1 and ad_type=3')
            ->field("ad_id,ad_name,ad_link,type,concat('$site_url',image) as image,concat('$site_url',video) as video")
            ->order('sort asc,ad_id desc')
            ->select()
            ->toArray();
        //获取公告信息
        $data ['notice'] = Essay::order('sort desc,id desc')->field('title,id')->select();
        //订单飘窗
        $arr = [];
        //认养订单
        $ry_order = FosterOrder::where("order_status > 0")
            ->field("user_id,pay_time")
            ->order('order_id desc')
            ->limit(10)->select()->each(function ($item) {
                $time = timediff($item->getData('pay_time'), time());
                $item['nickname'] = $item['user']['nickname'];
                $item['day'] = $time['day'];
                $item['hour'] = $time['hour'];
                $item['min'] = $time['min'];
                $item['sec'] = $time['sec'];
                unset($item['user'], $item['user_id'], $item['pay_time']);
                return $item;
            })->toArray();
        //商城订单
        $shop_order = Order::where("order_status > 0")
            ->field("user_id,pay_time")
            ->order('order_id desc')
            ->limit(10)->select()->each(function ($item) {
                $time = timediff($item->getData('pay_time'), time());
                $item['nickname'] = $item['user']['nickname'];
                $item['day'] = $time['day'];
                $item['hour'] = $time['hour'];
                $item['min'] = $time['min'];
                $item['sec'] = $time['sec'];
                unset($item['user'], $item['user_id'], $item['pay_time']);
                return $item;
            })->toArray();
        //交易大厅兑换商城订单
        $dh_order = ConvertOrder::where("order_status > 0")
            ->field("user_id,pay_time")
            ->order('order_id desc')
            ->limit(10)->select()->each(function ($item) {
                $time = timediff($item->getData('pay_time'), time());
                $item['nickname'] = $item['user']['nickname'];
                $item['day'] = $time['day'];
                $item['hour'] = $time['hour'];
                $item['min'] = $time['min'];
                $item['sec'] = $time['sec'];
                unset($item['user'], $item['user_id'], $item['pay_time']);
                return $item;
            })->toArray();
        //积分商城订单
        $jf_order = JifenOrder::where("order_status > 0")
            ->field("user_id,pay_time")
            ->order('order_id desc')
            ->limit(10)->select()->each(function ($item) {
                $time = timediff($item->getData('pay_time'), time());
                $item['nickname'] = $item['user']['nickname'];
                $item['day'] = $time['day'];
                $item['hour'] = $time['hour'];
                $item['min'] = $time['min'];
                $item['sec'] = $time['sec'];
                unset($item['user'], $item['user_id'], $item['pay_time']);
                return $item;
            })->toArray();
        if ($ry_order) {
            $arr = array_merge($arr, $ry_order);
        }
        if ($shop_order) {
            $arr = array_merge($arr, $shop_order);
        }
        if ($dh_order) {
            $arr = array_merge($arr, $dh_order);
        }
        if ($jf_order) {
            $arr = array_merge($arr, $jf_order);
        }
        $data['order_window'] = $arr;
        throw new MyException('获取成功', 10, $data);
    }

    /**
     * @Apidoc\Title("首页商品数据")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/IndexGoods")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",default="",desc="用户id")
     * @Apidoc\Param("is_cart",type="int",default="0",desc="是否是购物车")
     */
    public function index_goods()
    {
        //接收传递的分页信息：页数，和每页条数
        $site_url = SITE_URL;
        //初始数据字段
        $filed = "goods_id,concat('$site_url',goods_img) as goods_img,goods_price,seckill_price,goods_name,sales_sum";
        $filed2 = "goods_id,concat('$site_url',goods_img) as goods_img,goods_price,day_sy,sy_day,yield,goods_name,sales_sum,unit,store_count,store_id";
        $where1 = "is_on_sale=1 and is_recommend=1";
        $where2 = "is_on_sale=1 and is_recommend=1";
        $goods_model = new Goods();
        $foster_goods_model = new FosterGoods();
        //商品
        $goods1 = $goods_model->where($where1)
            ->field($filed)
            ->order('sort asc,goods_id desc')
            ->limit(20)
            ->select()->each(function ($item) {
                $item['price'] = $item['price'];
                return $item;
            })->toArray();
        //认养商品
        $ry_list = $foster_goods_model->where($where2)
            ->with(['store'])
            ->field($filed2)
            ->order('sort asc,goods_id desc')
            ->limit(20)
            ->select()->each(function ($item) {
                $item['take_num'] = $item['take_num_text'];
                $item['take_bili'] = $item['take_bili_text'];
                $item['head_urls'] = $item['take_user_head'];
                return $item;
            })->toArray();
        $data['goods1'] = $goods1;
        $data['ry_list'] = $ry_list;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("搜索记录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/Search")
     * @Apidoc\Param("user_id",type="int",default="1",desc="用户id")
     * @Apidoc\Returned("search", type="array",default="搜索记录",desc="【'乐高布加迪','变形金刚','遥控飞机'】")
     */
    public function search()
    {
        $user_id = input('user_id');
        $searchList = [];
        if ($user_id) {
            $goods_search = new GoodsSearch();
            $key_word = $goods_search->where('user_id', $user_id)->value('key_word');
            if ($key_word) {
                $searchList = explode(',', $key_word);
            }
        }
        $data['search'] = $searchList;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("搜索")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/SubSearch")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",default="1",desc="用户id")
     * @Apidoc\Param("goods_type",type="int",default="",desc="商品类型")
     * @Apidoc\Param("keyword",type="string",default="",desc="搜索关键字")
     * @Apidoc\Param("order",type="string",default="all",desc="排序:all/所有，sales/销量...")
     * @Apidoc\Param("sort",type="string",default="desc",desc="排序方式:desc/降序，asc/升序")
     * @Apidoc\Returned("goods", type="array",default="商品数据",desc="{goods_id:'商品id'，goods_img:'商品图片'，goods_price:'商品价格'，goods_name:'商品名称'，market_price:'商品市场价'，sales_sum:'销量'}")
     */
    public function sub_search()
    {
        $goods_model = new Goods();
        //接收传递的分页信息：页数，和每页条数
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        //搜索关键字
        $keyword = input('keyword');
        //用户id
        $user_id = input('user_id');
        //排序
        $order = input('order', 'all');
        //排序方式
        $sort = input('sort', 'desc');
        //商品类型
        $goods_type = input('goods_type');
        //初始条件：
        $where = "is_on_sale=1";
        //初始排序方式
        $orders = "goods_id desc";
        //初始数据字段
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,goods_price,goods_name,sales_sum,seckill_start_time,seckill_end_time,seckill_price,store_count";
        if ($keyword) {
            $where .= ' and goods_name like ' . "'%" . $keyword . "%'";
            //如果已进行登陆,则记录查询
            if ($user_id) {
                $search = GoodsSearch::where('user_id', $user_id)->find();
                if ($search) {
                    $arr = explode(',', $search['key_word']);
                    $key = array_search($keyword, $arr);
                    if (is_numeric($key)) {
                        unset($arr[$key]);
                        array_unshift($arr, $keyword);
                        $keyword = implode(',', $arr);
                    } else {
                        array_unshift($arr, $keyword);
                        $keyword = implode(',', $arr);
                    }
                    $k = ['user_id' => $user_id, 'key_word' => $keyword];
                    $search->save($k);
                } else {
                    $k = ['user_id' => $user_id, 'key_word' => $keyword];
                    GoodsSearch::insert($k);
                }
            }
        }
        if ($goods_type) {
            $where .= " and goods_type=$goods_type";
        }
        if ($order != 'all') {
            $orders = "{$order} {$sort}";
        }
        $goods = $goods_model->where($where)
            ->field($field)
            ->order($orders)
            ->page($pi, $ps)
            ->select()->each(function ($item) {
                $item['goods_price'] = $item['price'];
                return $item;
            });
        $data['list'] = $goods;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("清空搜索")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/EmptySearch")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     */
    public function empty_search()
    {
        //用户id
        $user_id = input('user_id');
        if ($user_id) {
            $res = GoodsSearch::where('user_id', $user_id)->delete();
        }
        if ($res) {
            throw new MyException('操作成功', 200);
        }
        throw new MyException('操作失败');
    }

    /**
     * @Apidoc\Title("获取商品1级分类")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/GoodsCate")
     * @Apidoc\Returned("classification", type="array",default="商品分类",desc="{}")
     */
    public function goods_cate()
    {
        $cateList = GoodsCategory::where('is_show=1 and parent_id=0')
            ->order('sort asc,id asc')
            ->field('id,name,image,parent_id')
            ->select()
            ->toArray();
        foreach ($cateList as $key => $val) {
            $val['image'] = $val['image'] ? SITE_URL . $val['image'] : SITE_URL . '/static/images/not_adv.png';
            $cateList[$key] = $val;
        }
        $data['classes'] = $cateList;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("1级分类商品数据")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/CateGoods")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("cat_id_1",type="int",require=true,default="0",desc="一级分类id 只传此参数则返回2级分类及商品")
     * @Apidoc\Param("cat_id_2",type="int",require=true,default="0",desc="二级分类id 当传入时则返回商品列表")
     * @Apidoc\Returned("goods", type="array",default="{}",desc="商品数据")
     */
    public function cate_goods()
    {
        //接收传递的分页信息：页数，和每页条数
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $cat_id_1 = input('cat_id_1');
        $cat_id_2 = input('cat_id_2');
        $goods_model = new Goods();
        $goods = [];
        //初始数据字段
        $field = "goods_id,concat('$this->site_url',goods_img) as goods_img,goods_price,seckill_price,goods_name,sales_sum";
        if ($cat_id_2) {
            $where = "is_on_sale=1 and cat_id_2=$cat_id_2";
            $goods = $goods_model->where($where)
                ->field($field)
                ->order('sort asc,goods_id asc')
                ->page($pi, $ps)
                ->select()->each(function ($item) {
                    $item['price'] = $item['price'];
                    return $item;
                })->toArray();
            $data['cates'] = [];
        } else {
            $cates = GoodsCategory::where('is_show=1 and parent_id=' . $cat_id_1)
                ->order('sort asc,id asc')
                ->field('id,name,image,parent_id')
                ->select()
                ->toArray();
            if ($cates) {
                $where = "is_on_sale=1 and cat_id_2={$cates[0]['id']}";
                $goods = $goods_model->where($where)
                    ->field($field)
                    ->order('sort asc,goods_id asc')
                    ->page($pi, $ps)
                    ->select()->each(function ($item) {
                        $item['price'] = $item['price'];
                        return $item;
                    })->toArray();
            }
            $data['cates'] = $cates;
        }
        $data['goods'] = $goods;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("登录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/do_login")
     * @Apidoc\Param("mobile", type="int", require=true, desc="手机号")
     * @Apidoc\Param("password", type="int",require=true, desc="密码")
     * @Apidoc\Returned("user", type="array",default="{}",desc="用户信息")
     */
    public function login()
    {
        $data = input('post.');
        try {
            validate(UserValidate::class)->scene('login')->check($data);
        } catch (ValidateException $e) {
            $error = $e->getError();
            throw new MyException($error);
        }
        $user = get_user_info($data['mobile'], 1);
        Db::name('users')->where("user_id", $user['user_id'])->update(['last_login' => time()]);
        $arr['user_id'] = $user['user_id'];
        $arr['token'] = $user['token'];

        throw new MyException('登录成功', 200, $arr);
    }

    /**
     * @Apidoc\Title("微信登录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/weixin_dl")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("openId",type="string",require=true,default="",desc="openId")
     * @Apidoc\Param("nickName",type="string",require=true,default="",desc="微信昵称")
     * @Apidoc\Param("gender",type="int",require=true,default="",desc="性别")
     * @Apidoc\Param("city",type="int",require=true,default="",desc="城市")
     * @Apidoc\Param("province",type="int",require=true,default="",desc="省份")
     * @Apidoc\Param("avatarUrl",type="int",require=true,default="",desc="微信头像")
     * @Apidoc\Param("unionId",type="int",require=true,default="",desc="unionId")
     */
    public function weixin_login()
    {
        $openId = input('openId');
        $unionId = input('unionId');
        $nickName = input('nickName');
        $gender = input('gender');
        $city = input('city');
        $province = input('province');
        $avatarUrl = input('avatarUrl');
        if (empty($openId) && empty($unionId)) {
            throw new MyException('提交参数有误');
        }
        $third_model = new ThirdUser();
        if ($unionId) {
            $third_find_where['unionid'] = $unionId;
        } else {
            $third_find_where['openid'] = $openId;
        }
        $third_find = $third_model->where($third_find_where)->find();
        if ($third_find) {
            $user = Users::find($third_find['uid']);
            if ($user) {
                $third_update['openid'] = $openId;
                $third_update['unionid'] = $unionId;
                $third_find->save($third_update);
                Db::name('users')->where("user_id", $user['user_id'])->update(['last_login' => time()]);
                $arr['user_id'] = $user['user_id'];
                $arr['token'] = $user['token'];
                throw new MyException('登录成功', 200, $arr);
            } else {
                $arr['tid'] = $third_find['id'];
                throw new MyException('请先绑定手机号', -100, $arr);
            }
        } else {
            //插入到第三方用户信息表
            $insert['type'] = 2;
            $insert['avatar'] = $avatarUrl;
            $insert['province'] = $province;
            $insert['city'] = $city;
            $insert['nick_name'] = $nickName;
            $insert['gender'] = $gender;
            $insert['openid'] = $openId;
            $insert['unionid'] = $unionId;
            $third_model->save($insert);
            $arr['tid'] = $third_model->id;
            throw new MyException('请先绑定手机号', -100, $arr);
        }
    }

    /**
     * @Apidoc\Title("绑定、注册")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/do_bind_mobile")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("tid",type="int",require=true,default="",desc="第三方用户")
     * @Apidoc\Param("mobile",type="string",require=true,default="",desc="手机号码")
     * @Apidoc\Param("code",type="int",default="",desc="验证码")
     * @Apidoc\Param("password",type="string",require=true,default="",desc="密码")
     * @Apidoc\Param("conpassword",type="string",require=true,default="",desc="确认密码")
     * @Apidoc\Param("rekey",type="string",require=true,default="",desc="推荐人")
     */
    public function bind_mobile()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2, 3])) {
            throw new MyException('提交参数有误');
        }
        $reg_bind_mobile = getSysConfig('sms.reg_bind_mobile');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        $mobile = input('mobile');
        $tid = input('tid');
        $third_model = new ThirdUser();
        if ($step == 1) {
            $return_data['reg_bind_mobile'] = $reg_bind_mobile;
            $return_data['sms_time_out'] = $sms_time_out;
            throw new MyException('获取成功', 10, $return_data);
        } elseif ($step == 2) {
            if (empty($tid)) {
                throw new MyException('提交参数有误');
            }
            $third_find = $third_model->find($tid);
            if (empty($third_find)) {
                throw new MyException('提交参数有误');
            }
            if (empty($mobile) || !check_mobile($mobile)) {
                throw new MyException('手机号码格式有误');
            }
            //看看是否已绑定其它用户
            if ($third_find['uid']) {
                $temp_user = Users::find($third_find['uid']);
                if ($temp_user) {
                    throw new MyException('该微信已绑定其它账户');
                }
            }
            $user = Users::where("mobile", $mobile)->find();
            if ($user) {
                //查询是否已绑定其它微信
                $temp_find_where['uid'] = $user['user_id'];
                $temp_find_where['type'] = 2;
                $temp_find = $third_model->where($temp_find_where)->find();
                if ($temp_find) {
                    throw new MyException('该账户已绑定其它微信');
                }
                $third_update['uid'] = $user['user_id'];
                $third_find->save($third_update);
                Db::name('users')->where("user_id", $user['user_id'])->update(['last_login' => time()]);
                $arr['user_id'] = $user['user_id'];
                $arr['token'] = $user['token'];
                throw new MyException('绑定成功', 100, $arr);
            } else {
                throw new MyException('请先注册', -100);
            }
        } else {
            if (empty($tid)) {
                throw new MyException('提交参数有误');
            }
            $third_find = $third_model->find($tid);
            if (empty($third_find)) {
                throw new MyException('提交参数有误');
            }
            //看看是否已绑定其它用户
            if ($third_find['uid']) {
                $temp_user = Users::find($third_find['uid']);
                if ($temp_user) {
                    throw new MyException('该微信已绑定其它账户');
                }
            }
            $data = input('post.');
            $data['sms'] = $reg_bind_mobile;
            try {
                validate(UserValidate::class)->scene('bindReg')->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $mobile = input('mobile');
            $password = input('password');
            $rekey = input('rekey');
            //通过user_id查找
            $reuser = get_user_info($rekey);
            $map['password'] = encrypt($password);
            $map['head_pic'] = '/resource/images/default.png';
            $map['nickname'] = $mobile;
            $map['realname'] = $data['realname_reg'];
            $map['mobile'] = $mobile;
            $map['reid'] = $reuser ? $reuser['user_id'] : 0;
            $map['jt_id'] = $reuser ? $reuser['reid'] : 0;
            $map['rekey'] = getReKey();
            $map['token'] = getToken();
            $map['reg_time'] = time();
            $res = Db::name('users')->insertGetId($map);
            if ($res) {
                $third_update['uid'] = $res;
                $third_find->save($third_update);
                //增加团队人数
                td_all_num($res);
                $arr['user_id'] = $res;
                $arr['token'] = $map['token'];
                throw new MyException('注册并绑定成功', 100, $arr);
            } else {
                throw new MyException('注册失败');
            }
        }
    }

    /**
     * @Apidoc\Title("注册")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/do_register")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("mobile",type="string",require=true,default="",desc="手机号码")
     * @Apidoc\Param("code",type="int",default="",desc="验证码")
     * @Apidoc\Param("password",type="string",require=true,default="",desc="密码")
     * @Apidoc\Param("conpassword",type="string",require=true,default="",desc="确认密码")
     * @Apidoc\Param("rekey",type="string",require=true,default="",desc="推荐人")
     * @throws \app\common\util\MyException
     */
    public function register()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $regis_sms_enable = getSysConfig('sms.regis_sms_enable');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        if ($step == 1) {
            $return_data['regis_sms_enable'] = $regis_sms_enable;
            $return_data['sms_time_out'] = $sms_time_out;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $data = input('post.');
            unset($data['user_id']);
            $data['sms'] = $regis_sms_enable;
            try {
                validate(UserValidate::class)->scene('reg')->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $mobile = input('mobile');
            $password = input('password');
            $rekey = input('rekey');
            //通过user_id查找
            $reuser = get_user_info($rekey);
            $map['password'] = encrypt($password);
            $map['head_pic'] = '/resource/images/default.png';
            $map['nickname'] = $mobile;
            $map['realname'] = $data['realname_reg'];
            $map['mobile'] = $mobile;
            $map['reid'] = $reuser ? $reuser['user_id'] : 0;
            $map['jt_id'] = $reuser ? $reuser['reid'] : 0;
            $map['rekey'] = getReKey();
            $map['token'] = getToken();
            $map['reg_time'] = time();


            Db::startTrans();
            try {
                Users::create($map);
                Db::commit();
            } catch (\Throwable $throwable) {
                Db::rollback();
                abort(400, $throwable->getMessage());
            }
            throw new MyException('注册成功', 200);
        }
    }

    /**
     * @Apidoc\Title("找回密码")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/do_forget")
     * @Apidoc\Param("mobile", type="int", require=true, desc="手机号")
     * @Apidoc\Param("code", type="int",require=true, desc="验证码")
     * @Apidoc\Param("password", type="int",require=true, desc="密码")
     * @Apidoc\Param("conpassword", type="int",require=true, desc="确认密码")
     */
    public function forget_pwd()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        if ($step == 1) {
            $return_data['sms_time_out'] = $sms_time_out;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $data = input('post.');
            try {
                validate(UserValidate::class)->scene('forget')->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $user = get_user_info($data['mobile'], 1);
            $update['password'] = encrypt($data['password']);
            $res = Users::where('user_id', $user['user_id'])->update($update);
            if ($res !== false) {
                throw new MyException('密码重置成功', 200);
            } else {
                throw new MyException('密码重置失败');
            }
        }
    }

    /**
     * @Apidoc\Title("公告列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/GetEssay")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id", type="int",default="1",desc="用户id")
     * @Apidoc\Returned("essay", type="array",default="{}",desc="公告数据")
     */
    public function get_essay()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $lists = Db::name('essay')
            ->where('open=1')
            ->order('sort asc,id desc')
            ->page($pi, $ps)
            ->field('id,title,description,image,update_time')
            ->select();
        if (!empty($lists)) {
            foreach ($lists as $key => $val) {
                $val['image'] = $val['image'] ? SITE_URL . $val['image'] : SITE_URL . '/static/images/not_adv.png';
                $val['update_time'] = date('y-m-d ', $val['update_time']);
                $lists[$key] = $val;
            }
        }
        $data['essay'] = $lists;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("公告详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/EssayDetail")
     * @Apidoc\Param("essay_id", type="int",default="1",desc="公告id")
     */
    public function essay_detail()
    {
        $essay_id = input('essay_id');
        $art = Db::name('essay')->where('id', $essay_id)->find();
        if (empty($art) || $art['open'] == 0) {
            return view('api/empty');
        }
        View::assign('art', $art);
        return view('content/essay_detail');
    }

    /**
     * @Apidoc\Title("协议详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/xieyi_xq")
     * @Apidoc\Param("id", type="int",default="",desc="协议id")
     */
    public function protocol_detail()
    {
        $id = input('id');
        $art = Db::name('protocol')->where('id', $id*config('site.uniacid'))->find();

        if (empty($art)) {
            return view('api/empty');
        }
        View::assign('art', $art);
        return view('content/protocol_detail');
    }

    /**
     * @Apidoc\Title("认养协议详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/ry_xieyi_xq")
     * @Apidoc\Param("gid", type="int",default="",desc="商品id")
     * @Apidoc\Param("oid", type="int",default="",desc="订单id")
     */
    public function ry_protocol_detail()
    {
        $gid = input('gid');
        $oid = input('oid');
        if (empty($gid) && empty($oid)) {
            return view('api/empty');
        }
        if ($gid) {
            $goods_agreement = Db::name('foster_goods')->where('goods_id', $gid)->value('goods_agreement');
        } else {
            $goods_agreement = Db::name('foster_order')->where('order_id', $oid)->value('goods_agreement');
        }
        View::assign('goods_agreement', $goods_agreement);
        return view('content/ry_protocol_detail');
    }
}
